//package CalendarLogic;

import java.util.*;
import java.lang.*;
import java.text.*;
import java.io.*;

public class CalLogic {
	private final static String DATE_FORMAT = "MM/dd/yyyy";
	private final static String CAL_DATE_FORMAT = "yyyyMMdd";
	private final static String TIME_FORMAT = "hh:mm a";
	private final static String CAL_TIME_FORMAT = "HHmm";

	private final static int BEFORE = -1;
	private final static int EQUAL = 0;
	private final static int AFTER = 1;

	/**
	 * Constructor for CalLogic
	 */
	public CalLogic() {
	}

	/**
	 * Returns the priority as a number
	 * 
	 * @param priority
	 * @return
	 */
	public String convertPriority(String priority) {
		if (priority.equalsIgnoreCase("LOW"))
			return "6";
		else if (priority.equalsIgnoreCase("MEDIUM"))
			return "5";
		else if (priority.equalsIgnoreCase("HIGH"))
			return "1";
		else
			return "0";
	}

	/**
	 * Checks if the given date is of the format MM/dd/yyyy
	 * 
	 * @param date
	 * @throws Exception
	 */
	public void validDate(String date) throws Exception {
		DateFormat df = new SimpleDateFormat(DATE_FORMAT);
		df.setLenient(false);

		df.parse(date);
	}

	/**
	 * Converts the given date to the .ics date format
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public String convertDate(String date) throws Exception {
		DateFormat original = new SimpleDateFormat(DATE_FORMAT);
		DateFormat convert = new SimpleDateFormat(CAL_DATE_FORMAT);

		Date caldate = original.parse(date);

		return convert.format(caldate);
	}

	/**
	 * Compares input from with input to and returns: 1 if to is after from 0 if
	 * to is the same as from -1 if to is before from
	 * 
	 * @param from
	 * @param to
	 * @return
	 * @throws Exception
	 */
	public int compareDates(String from, String to) throws Exception {
		DateFormat date = new SimpleDateFormat(CAL_DATE_FORMAT);

		Date fromdate = date.parse(from);
		Date todate = date.parse(to);

		if (todate.after(fromdate))
			return 1;
		else if (todate.equals(fromdate))
			return 0;
		else
			return -1;
	}

	/**
	 * Checks the given time is a valid time of the format hh:mm am/pm
	 * 
	 * @param time
	 * @throws Exception
	 */
	public void validTime(String time) throws Exception {
		DateFormat df = new SimpleDateFormat(TIME_FORMAT);
		df.setLenient(false);

		df.parse(time);
	}

	/**
	 * Converts the given time format to a .ics time format
	 * 
	 * @param time
	 * @return
	 * @throws Exception
	 */
	public String convertTime(String time) throws Exception {
		DateFormat original = new SimpleDateFormat(TIME_FORMAT);
		DateFormat convert = new SimpleDateFormat(CAL_TIME_FORMAT);

		Date caltime = original.parse(time);

		return convert.format(caltime) + "00";
	}

	/**
	 * Compares input from with input to and returns true if to is after from
	 * 
	 * @param from
	 * @param to
	 * @return
	 * @throws Exception
	 */
	public boolean compareTimes(String from, String to) throws Exception {
		DateFormat time = new SimpleDateFormat(CAL_TIME_FORMAT);

		Date fromtime = time.parse(from);
		Date totime = time.parse(to);

		return totime.after(fromtime);
	}

	/**
	 * Returns the users current timezone
	 * 
	 * @return
	 */
	public String getTimeZone() {
		DateFormat myDate = new SimpleDateFormat();

		return myDate.getTimeZone().getID();
	}

	public boolean validLat(String latstr) throws Exception {
		float lat = Float.parseFloat(latstr);

		if ((lat > 90.0 || lat < -90.0))
			return false;
		else
			return true;
	}

	public boolean validLng(String lngstr) throws Exception {
		float lng = Float.parseFloat(lngstr);

		if ((lng > 180.0 || lng < -180.0))
			return false;
		else
			return true;
	}

	/**
	 * Converts the given inputs to a .ics file format
	 * 
	 * @param input
	 */
	public void toICSFile(StoreInput input) {
		String errors = new String("The Following Inputs Were Incorrect:\n\n\t");
		String noerrors = errors;

		try {
			validDate(input.getFromDate());
			input.setFromDate(convertDate(input.getFromDate()));
		} catch (Exception e) {
			errors += "FROM DATE\n\t";
		}
		try {
			validDate(input.getToDate());
			input.setToDate(convertDate(input.getToDate()));
		} catch (Exception e) {
			errors += "TO DATE\n\t";
		}
		try {
			validTime(input.getFromTime());
			input.setFromTime(convertTime(input.getFromTime()));
		} catch (Exception e) {
			errors += "FROM TIME\n\t";
		}
		try {
			validTime(input.getToTime());
			input.setToTime(convertTime(input.getToTime()));
		} catch (Exception e) {
			errors += "TO TIME\n\t";
		}

		if (errors.equals(noerrors)) {
			try {
				if (compareDates(input.getFromDate(), input.getToDate()) == EQUAL) {
					if (!compareTimes(input.getFromTime(), input.getToTime()))
						throw new Exception();
				} else if (compareDates(input.getFromDate(), input.getToDate()) == BEFORE) {
					throw new Exception();
				}
			} catch (Exception e) {
				errors += "INPUTS ARE NOT CHRONOLOGICAL\n\t";
			}
		}

		try {
			if (!validLat(input.getLatitude()))
				errors += "LATITUDE\n\t";
		} catch (Exception e) {
			errors += "LATITUDE\n\t";
		}

		try {
			if (!validLng(input.getLongitude()))
				errors += "LONGITUDE\n\t";
		} catch (Exception e) {
			errors += "LONGITUDE\n\t";
		}

		input.setTimezone(getTimeZone());
		input.setPriority(convertPriority(input.getPriority()));
		input.setPrivacy(input.getPrivacy().toUpperCase());

		if (errors.equals(noerrors)) {
			String filename = input.getFileName();

			if (!filename.endsWith(".ics"))
				filename += ".ics";

			PrintWriter outputstream = null;
			try {
				outputstream = new PrintWriter(filename);
			} catch (Exception e) {
				System.out.println("Could not open file " + filename);
			}

			outputstream.println("BEGIN:VCALENDAR");
			outputstream.println("VERSION:2.0");
			outputstream.println("BEGIN:VEVENT");
			outputstream.println("CLASS:" + input.getPrivacy());
			outputstream.println("LOCATION:" + input.getLocation());
			outputstream.println("GEO:" + input.getLatitude() + ";"
					+ input.getLongitude());
			outputstream.println("PRIORITY:" + input.getPriority());
			outputstream.println("SUMMARY:" + input.getSummary());
			outputstream.println("DTSTART;TZID=" + input.getTimezone() + ":"
					+ input.getFromDate() + "T" + input.getFromTime() + "Z");
			outputstream.println("DTEND;TZID=" + input.getTimezone() + ":"
					+ input.getToDate() + "T" + input.getToTime() + "Z");
			outputstream.println("END:VEVENT");
			outputstream.println("END:VCALENDAR");

			outputstream.close();
		} else
			System.out.println(errors);
	}
}
